import React, {Component} from "react";
import './login.less';
import logo from '../../assets/images/logo.png';
import { Form, Icon, Input, Button, message } from 'antd';
import {reqLogin} from '../../api/index';
import memoryUtils from "../../utils/memoryUtils";
import storageUtils from "../../utils/storageUtils";
import {Redirect} from "react-router-dom";
import {connect} from 'react-redux';
import {login} from '../../redux/actions'

class Login extends Component{

    handleSubmit = (event) => {
        event.preventDefault();

        this.props.form.validateFields((err, values) => {
            if (!err) {
                const {username, password} = values;
                this.props.login(username, password);

            } else {
                console.log('校验失败')
            }
        });

        /* react版本写法
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                const {username, password} = values;
                const result = await reqLogin(username, password);
                console.log("请求成功：", result);
                if (result.status === 0) {
                    message.success('登录成功');
                    const user = result.data;
                    memoryUtils.user = user;
                    storageUtils.saveUser(user);
                    this.props.history.replace('/');
                } else {
                    message.error(result.msg)
                }
            } else {
                console.log('校验失败')
            }
        });*/
    };

    validatePwd = (rule, value, callback) => {
        if (!value) {
            callback('请输入密码');
        } else if (value.length < 4) {
            callback('密码至少为4位');
        } else if (value.length > 12) {
            callback('密码至多为12位')
        } else if (!/^[0-9a-zA-Z_]+$/.test(value)){
            callback('密码必须是大写字母、小写字母、数字组合');
        } else {
            callback();
        }
    };

    render() {
        //const user = memoryUtils.user;
        const user = this.props.user;
        if (user && user._id) {
            return <Redirect to='/home' />
        }
        const errorMsg = this.props.user.errorMsg;

        const form = this.props.form;
        const { getFieldDecorator } = form;

        return (
            <div className='login'>
                <header className='login-header'>
                    <img src={logo} alt='logo'></img>
                    <h1>React项目:后台管理系统</h1>
                </header>
                <section className='login-content'>
                    <div className={user.errorMsg ? 'error-msg show' : 'error-msg'}>{user.errorMsg}</div>
                    <h2>用户登录</h2>
                    <Form onSubmit={this.handleSubmit} className="login-form">
                        <Form.Item>
                            {getFieldDecorator('username', {
                                rules: [
                                    { required: true, whitespace: true, message: '请输入用户名' },
                                    { min: 4, message: '用户名最小长度为4' },
                                    { max: 12, message: '用户名最大长度为12' },
                                    { pattern: /^[0-9a-zA-Z_]+$/, message: '用户名必须是大写字母、小写字母、数字组合' }
                                ],
                                initialValue: 'admin'
                            })(
                                <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />,
                            )}
                        </Form.Item>
                        <Form.Item>
                            {getFieldDecorator('password', {
                                rules: [{ validator: this.validatePwd }],
                            })(
                                <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码"/>,
                            )}
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className="login-form-button">登录</Button>
                        </Form.Item>
                    </Form>
                </section>
            </div>
        );
    }
}

const WrapLogin = Form.create()(Login);

export default connect(
    state => ({user: state.user}),
    {login}
)(WrapLogin)